package com.attilax.device;

 
 
 
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.attilax.concur.TaskUtil;
import com.attilax.dataspider.TsaolyoNetDataSpider;
import com.sun.management.OperatingSystemMXBean;

public class CpuUtilV2 {
	public static final Logger logger = LoggerFactory
			.getLogger(TsaolyoNetDataSpider.class);

	public static void main(String[] args) {
		while(true)
		{
			cpu();
			TaskUtil.sleep(1000);
		}
		
	}

	private static void cpu() {
		//采集CPU利用率需要自己计算一下，因为API只提供了获取cpu的使用时间，我得在两次系统时间间隔内获取两次CPU的使用时间，得到在该时间间隔内cpu使用的时间，相除即得到CPU的使用率，当然误差肯定存在。

		//计算cpu使用率代码  收藏代码
//		JMXConnector conn = JMXConnectorFactory.connect(serviceURL);  
//		MBeanServerConnection mbs=conn.getMBeanServerConnection();  
//		com.sun.management.OperatingSystemMXBean opMXbean =   
//				ManagementFactory.newPlatformMXBeanProxy(mbs,                 
//				ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class);  
		com.sun.management.OperatingSystemMXBean opMXbean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
		        Long start = System.currentTimeMillis();  
		        long startT = opMXbean.getProcessCpuTime();  
		        /**    Collect data every 5 seconds      */  
		        try {  
		          //  TimeUnit.SECONDS.sleep(50);  
		        	TimeUnit.MILLISECONDS.sleep(50);
		        } catch (InterruptedException e) {  
		            logger.error("InterruptedException occurred while MemoryCollector sleeping...");  
		        }  
		        Long end = System.currentTimeMillis();  
		        long endT = opMXbean.getProcessCpuTime();  
		//end - start 即为当前采集的时间单元，单位ms  
		//endT - startT 为当前时间单元内cpu使用的时间，单位为ns  
		//所以：  1s=1000ms1ms=1000us1us=1000ns
		        int availableProcessors = opMXbean.getAvailableProcessors();
		        double  spanT=(endT-startT)/1000000.0; //calc as ms
				long span = end-start;
				double ratie_total=spanT/span;
				System.out.println("ratie_total:"+String.valueOf(ratie_total));
				double ratio = ratie_total/availableProcessors ; 
				System.out.println("ratio:"+String.valueOf(ratio));
	}
}
